<template>
  <ClDialog v-bind="$attrs" :title="getTitle" width="1390px">
    <ClBar :loading="loaded">
      <h6>新增评审项模板：</h6>
      <ClForm ref="refTemplateForm" label-width="150px" :form-item="formItem" :disabled="disabled" />
      <h6>新增评审项：</h6>
      <AddRowForm
        v-for="(item, index) in addRowFormList"
        :key="item.id"
        ref="addRowFormRef"
        :short-no="index + 1"
        :initial-value="item"
        :disabled="disabled"
        :show-add-btn="index === addRowFormList.length - 1"
        :item-id-enum="itemIdEnum"
        @delete="handleDelete(index)"
        @add="handleAdd"
      />
    </ClBar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('atClose')">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="onSure">确定</el-button>
      </span>
    </template>
  </ClDialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { ADD_TEMPLATE_FORM_ITEM } from '../data'
import AddRowForm from './AddRowForm.vue'
import { getReviewItemList, getReviewTemplateView, postReviewTemplateSaveUpdate } from '@/api/basic-settings-module'

const refTemplateForm = ref<any>(null)
const addRowFormRef = ref<any>(null)

onMounted(() => {
  initForm()
})
const getItemIdEnum = async () => {
  const { rows }: any = await getReviewItemList({})
  return rows.map((item) => ({
    key: item.id,
    value: `名字：${item.name}；备注：${item.description}`,
    realValue: item.name
  }))
}
const getItemIdEnumName = (key: string) => {
  return itemIdEnum.value.find((item) => item.key === key)?.realValue
}
const { getYesOrNoEnum, getEnumValue } = useEnumeration()
const itemIdEnum = ref<any[]>([])
const loaded = ref(false)
const initForm = async () => {
  try {
    loaded.value = false
    const yesOrNoEnum = await getYesOrNoEnum()
    itemIdEnum.value = await getItemIdEnum() // 获取 评分点 下拉

    if (props.info.id) {
      const info: any = await getReviewTemplateView({ id: props.info.id })
      formItem.value.forEach((item) => (item.value = info[item.key]))
      addRowFormList.value = info.bandList
    }
    formItem.value.forEach((item) => {
      if (item.key === 'secondPhaseCode') {
        item.elementConfig.options = yesOrNoEnum
      }
    })
    loaded.value = true
  } catch (error) {
    loaded.value = true
    console.log(error)
  }
}
const onSure = async () => {
  const res = await Promise.all([
    refTemplateForm.value.refElForm.validate(),
    ...addRowFormRef.value.map((item) => item.refAddRowForm.refElForm.validate())
  ])
  if (res.every((item) => item === true)) {
    const res1 = {
      ...refTemplateForm.value.formData,
      secondPhaseName: getEnumValue(refTemplateForm.value.formData.secondPhaseCode, 'yesOrNoEnum')
    }
    const res2 = addRowFormRef.value.map((item) => {
      return {
        ...item.refAddRowForm.formData,
        flowOrderName: getEnumValue(item.refAddRowForm.formData.flowOrderCode, 'flowOrderEnum'),
        itemName: getItemIdEnumName(item.refAddRowForm.formData.itemId)
      }
    })
    await postReviewTemplateSaveUpdate({ id: props.info.id, ...res1, bandList: res2 })
    emit('atClose', 'refresh-table')
  } else {
    ElMessage.warning('表单验证不通过')
  }
}
const formItem = ref(cloneDeep(ADD_TEMPLATE_FORM_ITEM))
// 新增评审项 表单列表
const addRowFormList = ref([
  {
    id: 'test1',
    orderNo: new Date().getTime()
  }
])
const handleDelete = (index: number) => {
  if (addRowFormList.value.length === 1) {
    ElMessage.warning('至少保留一个评审项')
    return
  }
  addRowFormList.value.splice(index, 1)
}
const handleAdd = () => {
  const newKey = `${new Date().getTime()}`
  addRowFormList.value.push({
    id: `key_${newKey}`,
    orderNo: new Date().getTime()
  })
}

const getTitle = computed(() => {
  return props.type
})

interface infoType {
  [props: string]: any
}
const props = defineProps<{ info: infoType; type: string }>()
const disabled = computed(() => {
  return props.info.disabled || false
})
const emit = defineEmits<{
  (e: 'atClose', str?: string | undefined): void
  (e: 'reFreshTable', str?: string | undefined): void
}>()
</script>

<style scoped lang="scss"></style>
